package nl.will.dirstat;

import java.io.File;
import java.io.IOException;

public class DirStatAppl {
	private static String rootDirName = "D:/";

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		// Directory rootDirectory = new Directory("c:/IBM");
		System.out.println("Initializing root directory " + rootDirName);
		Directory rootDirectory = new Directory(rootDirName);
		new Visualizer(rootDirectory).printDirectoryToConsole();
		System.out.println("Ready to show directory statistics");
		boolean quit = false;
		while (!quit) {

			System.out.print("> ");
			byte[] bytes = new byte[1024];
			try {
				System.in.read(bytes);

			} catch (IOException e) {
				throw new RuntimeException(e);
			}
			String[] commands = new String(bytes).trim().split(" ");

			if (null != commands) {

				String directoryKey = getDirectoryPath(commands);
				int sumOfDirsToShow = getSumOfDirsToShow(commands);

				if ("quit".equalsIgnoreCase(commands[0])) {
					System.out.println("Stop directory statistics");
					quit = true;
				} else {
					Directory subDirectory = rootDirectory.getSubDirectory(directoryKey);
					if (subDirectory != null) {
						new Visualizer(subDirectory, sumOfDirsToShow).printDirectoryToConsole();
					} else {
						System.out.println("Directory not found");
					}
				}
			} else {
				System.out.println("No commands entered");
			}
		}

	}

	private static String getDirectoryPath(String[] commands) {
		if (commands.length > 0) {
			File file = new File(commands[0]);
			try {
				return file.getCanonicalPath();
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}
		return rootDirName;
	}

	private static int getSumOfDirsToShow(String[] commands) {
		int sumOfDirsToShow = 10;
		if (commands.length > 1) {
			try {
				sumOfDirsToShow = Integer.parseInt(commands[1]);
			} catch (NumberFormatException e) {
				System.out.println("Not a valid nummber of dirs; 10 will be used as default");
			}
		}
		return sumOfDirsToShow;
	}

}
